/**
 * 用于分页
 *
 * @author winkyle
 * @date 2018/9/10
 */
var parseParam = function(param, key) {
    var paramStr = "";
    if (param instanceof String || param instanceof Number || param instanceof Boolean) {
        paramStr += "&" + key + "=" + param;
    } else {
        $.each(param, function(i) {
            var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
            paramStr += '&' + parseParam(this, k);
        });
    }
    return paramStr.substr(1);
};

function LoadPage(container,url,params,field,draw,listener) {
    var pageBar = field['pageBar'];
    //每页记录数、第几页、跳转、上一页、下一页、首页、尾页、页码条、单个页码（函数）
    var changeCount,toGoPage,jump,prePage,nextPage,first,end,current,currentBar;
    if(field['pageBar'] == null){
        changeCount = $("#changeCount");
        toGoPage = $("#toGoPage");
        jump = $("#jump");
        prePage = $("#prePage");
        nextPage = $("#nextPage");
        first = $("#first");
        end = $("#end");
        current = $("#current");
        currentBar = function (i,isCurrentPage) {
            var li;
            if (isCurrentPage) {
                li = $("<li class='current active' value='" + i + "'><a><font>" + i + "</font></a>");
            } else {
                li = $("<li class='current' style='cursor: default;' value='" + i + "'><a><font>" + i + "</font></a>");
            }
            return li;
        };
    }else{
        changeCount = pageBar['changeCount'];
        toGoPage = pageBar['toGoPage'];
        jump = pageBar['jump'];
        prePage = pageBar['prePage'];
        nextPage = pageBar['nextPage'];
        first = pageBar['first'];
        end = pageBar['end'];
        current = pageBar['current'];
        currentBar = pageBar['currentBar'];
    }
    var total=0;
    var values = params;
    var page={};
    page.start = 0;
    page.sortField = field['sortField'];
    page.orderDir = field['orderDir'];
    if (field['limit'] == null) {
        page.length = 10;
        if(changeCount!=null) {
            changeCount.append($("<option value='10'>10</option>"));
            changeCount.append($("<option value='20'>20</option>"));
            changeCount.append($("<option value='30'>30</option>"));
            changeCount.append($("<option value='40'>40</option>"));
            changeCount.append($("<option value='50'>50</option>"));
            changeCount.append($("<option value='60'>60</option>"));
            changeCount.val(10);
        }
    } else {
        page.length = field['limit'][0]-0;
        if(changeCount!=null) {
            for (var i = 0; i < field['limit'].length; i++) {
                changeCount.append($("<option value=" + field['limit'][i] + ">" + field['limit'][i] + "</option>"));
            }
            changeCount.val(field['limit'][0]);
        }
    }
    if(changeCount!=null) {
        changeCount.change(function () {
            if(toGoPage!=null) {
                toGoPage.val(1);
            }
            page.start = 0;
            page.length = changeCount.val()-0;
            ajax();
        });
    }
    if(toGoPage!=null) {
        toGoPage.val(1);
        toGoPage.change(function () {
            if (toGoPage.val() <= 0 || total == 0) {
                toGoPage.val(1);
            } else {
                var endPage = getEndPage();
                if (toGoPage.val() > endPage) {
                    toGoPage.val(endPage);
                }
            }
        });
        jump.click(function () {
            if((toGoPage.val()-1)*page.length<total){
                page.start = (toGoPage.val()-1)*page.length;
                ajax();
            }
        });
    }
    if(prePage!=null) {
        prePage.click(function () {
            page.start = page.start - page.length;
            ajax();
        });
    }
    prePage.hide();
    if(nextPage!=null) {
        nextPage.click(function () {
            page.start = page.start+page.length;
            ajax();
        });
    }
    nextPage.hide();
    if(first!=null) {
        first.click(function () {
            page.start = 0;
            ajax();
        });
    }
    if(end!=null) {
        end.click(function () {
            var endPage = getEndPage();
            page.start = (endPage - 1) * page.length;
            ajax();
        });
    }
    if(current!=null) {
        current.append(currentBar(1,true));
        addCurrentListener();
    }
    var ajax = function () {
        console.log(page);
        console.log(values);
        $.ajax({
            type: "POST",
            url: url,
            cache: false,	//禁用缓存
            data: $.extend({},values,page),	//传入已封装的参数
            dataType: "json",
            success: function (data) {
                console.log(data);
                if(data.success==true) {
                    total = data.recordsTotal;
                    container.empty();
                    if(draw == null){
                        for (var i = 0; i < data.data.length; i++) {
                            //todo 默认的表格样式加载
                            if(listener['row'] != null) {
                                listener['row'](data.data[i]);
                            }
                        }
                        if(listener['all'] != null) {
                            listener['all'](data.data[i]);
                        }
                    }else {
                        for (var i = 0; i < data.data.length; i++) {
                            container.append(draw(data.data[i]));
                            if(listener['row'] != null) {
                                listener['row'](data.data[i]);
                            }
                        }
                        if(listener['all'] != null) {
                            listener['all'](data);
                        };
                    }
                    var endPage = getEndPage();
                    var currentPage = page.start / page.length + 1;
                    if(currentPage!=1){
                        prePage.show();
                    }else{
                        prePage.hide();
                    }
                    if(currentPage!=endPage&&total!=0){
                        nextPage.show();
                    }else{
                        nextPage.hide();
                    }
                    if(current!=null) {
                        current.empty();
                        var currentStart, currentEnd;
                        if (currentPage - 2 < 1) {
                            if (currentPage - 1 < 1) {
                                currentStart = 1;
                            } else {
                                currentStart = currentPage - 1;
                            }
                        } else {
                            currentStart = currentPage - 2;
                        }
                        if (currentPage + 2 > endPage) {
                            if (currentPage + 1 > endPage) {
                                currentEnd = endPage;
                            } else {
                                currentEnd = currentPage + 1;
                            }
                        } else {
                            currentEnd = currentPage + 2;
                        }
                        for (var i = currentStart; i <= currentEnd; i++) {
                            var isCurrentPage;
                            if (i == currentPage) {
                                isCurrentPage = true;
                            } else {
                                isCurrentPage = false;
                            }
                            current.append(currentBar(i,isCurrentPage));
                        }
                        addCurrentListener();
                    }
                }else{
                    //弹提示框
                    prompt_alert('error',data.msg,1);
                    //callback(null);
                }
            }
        });
    }
    ajax();
    function addCurrentListener() {
        $(".current").click(function () {
            if (($(this).val() - 1) * page.length < total) {
                page.start = ($(this).val() - 1) * page.length;
                ajax();
            }
        });
    }
    function getEndPage() {
        var remainder = total%page.length;
        var endPage;
        if(remainder==0){
            endPage = total/page.length;
        }else{
            endPage = (total-remainder)/page.length+1;
        }
        return endPage;
    }
    return function (params) {
        values = params;
        ajax();
    }
}